package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"novel/cache"
	"novel/models"
	"novel/pkg"
	"time"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Register() {
	var err error
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"mes":  "注册填写不能为空",
		}
		c.ServeJSON()
		return
	}
	users := models.User{
		Username: username,
		Password: pkg.Md5(password),
	}
	if err = users.GetUsernameByUser(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"mes":  "系统错误",
		}
		c.ServeJSON()
		return
	}
	if users.ID > 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"mes":  "用户已存在",
		}
		c.ServeJSON()
		return
	}
	if err = users.Create(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"mes":  "请先去注册用户",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{

		"code": 200,
		"mes":  "注册成功",
	}
	c.ServeJSON()
	return
}
func (c *UserController) Login() {
	var err error
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"mes":  "注册填写不能为空",
		}
		c.ServeJSON()
		return
	}
	users := models.User{
		Username: username,
		Password: password,
	}
	key := "password_count_error" + username
	count, _ := cache.Rdb.Get(cache.Ctx, key).Int()
	if count >= 3 {
		cache.Rdb.Expire(cache.Ctx, key, time.Minute*2)
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"mes":  "密码错误三次用户封禁；两分钟",
		}
		c.ServeJSON()
		return
	}
	if err = users.GetUsernameByUser(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"mes":  "系统错误",
		}
		c.ServeJSON()
		return
	}
	if users.ID == 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"mes":  "用户不存在",
		}
		c.ServeJSON()
		return
	}

	if users.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, key)
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"mes":  "密码错误",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{

		"code": 200,
		"mes":  "登陆成功",
	}
	c.ServeJSON()
	return
}
